<?php
/*
Plugin Name: BUETian.com OAuthLogin for Facebook/Google+/etc...
Plugin URI: http://code.google.com/p/buetian-dot-com-theme-wordpress/
Description: Initially developed for http://www.buetian.com, this plugin allow users to login via any oauth provider site. Currently Google and Facebook are supported.
Author: seoul
Author URI: http://www.mythicangel.com
Version: 1.3
*/
include_once ("myan_oauth_information.php");

function myan_goauth_redirect(){
?>
<!doctype html>
<html><head>
</head>
<body>
Choose an option...
<script type="text/javascript">
(function(){
try{
	var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
	while (m = regex.exec(queryString)) {
		params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	//console.log(params);
	if( !!params.error)
	{
		alert(params.error);
		window.location = "<?PHP bloginfo('url'); ?>";
	}
	else if (params['state'] != null) {
		// return control to main window by calling a function of that window
		var r;
		var oauthStateInfo = params['state'].split("_", 2);
		var redirectURI = "<?PHP bloginfo('wpurl') ?>/wp-admin/admin-ajax.php?action=myan_oauthWordpress_login"+'&access_token='+params['access_token']+"&redirect_uri="+encodeURIComponent(oauthStateInfo[1])+"&provider="+oauthStateInfo[0];
		
		if(oauthStateInfo[0] == 'facebook')
		{
			r=confirm("You will be redirected to login process now.\n\nPlease note that, you are also logged into your Facebook account. Do you want to logout from Facebook now?\n\nOK= Logout from Facebook. \nCancel= Continue with Facebook");
			if(r)
				window.open("https://m.facebook.com/#footer");
		}
		else if(oauthStateInfo[0] == 'google')
		{
			r=confirm("You will be redirected to login process now.\n\nPlease note that, you are also logged into your Gmail account. Do you want to logout from Gmail now?\n\nOK= Logout from Gmail. \nCancel= Continue with Gmail");
			
			if(r)
				window.open("https://www.google.com/accounts/Logout");	
		}
		window.location = redirectURI;
	} else {
		alert("Your browser seems to be stopping this window from communicating with the main window.");
		window.location = "<?PHP bloginfo('url'); ?>";
	}
}catch(e)
{
	if(console)
		console.log(e);
}
})();

</script>
</body>
</html>
<?PHP
die;
}
add_action('wp_ajax_myan_goauth_login', 'myan_goauth_redirect');
add_action('wp_ajax_nopriv_myan_goauth_login', 'myan_goauth_redirect');

function myan_oauthWordpress_login_callback()
{
	try{
		if( !isset($_GET['access_token']) || !isset($_GET['redirect_uri']) || !isset($_GET['provider']) )
			throw new Exception('Redirect uri or OAUTH-Provider or Access token not found');
		$url = urldecode($_GET['redirect_uri']);
		$token= $_GET['access_token'];
		$provider = $_GET['provider'];
		
		if( $token == null || parse_url($url,PHP_URL_HOST) == '')
			throw new Exception('Redirect uri or Access token must have values');
		
		$oauth = new myan_OAuth_Information($provider);
		$userDataFromServer = $oauth->php_generic_validateToken($token);
		
		$username = 's' . $userDataFromServer->id;
		if($userDataFromServer->displayName == '')
			$userDataFromServer->displayName = $username;
		
		$password = returnOAuthPasswordByCreatingUser($username, $userDataFromServer->displayName, $provider);
		$userObject= get_user_by( 'login', $username );
		if(wp_check_password( $password, $userObject->user_pass, $userObject->ID) == false)
			wp_set_password( $password, $userObject->id );		
		
		$creds = array();
		$creds['user_login'] = $username;
		$creds['remember'] = true;
		$creds['ID'] = $userObject->id;
		$creds['display_name']= $userDataFromServer->displayName;
		$creds['first_name'] = $userDataFromServer->displayName;
		$creds['user_password'] = $password;
		//even if a user change password, it should be updated here
		$user = wp_update_user($creds);
		if(is_wp_error($user))
			throw new Exception($user->get_error_message());
		update_user_meta($userObject->id, 'oauth_user_profile_pic', $userDataFromServer->profile_pic);
		update_user_meta($userObject->id, 'oauth_user_link', $userDataFromServer->link);
		
		$user = wp_signon( $creds, true );			
		if( is_wp_error($user) )
			throw new Exception($user->get_error_message());
		
		$home = urldecode($_GET['redirect_uri']);
		echo "<html><head><meta http-equiv='refresh' content='1; url=$home'></head><body>Redirecting...</body></html>";
	}
	catch(Exception $e)
	{
		//echo '<strong>Caught exception:</strong> ',  $e->getMessage(), "\n";
		//header('412 Precondition Failed');
		header('Location: '. get_bloginfo('url').'?p=-9999&error='. urlencode($e->getMessage()) );
	}
	DIE;
}

// Apply filter
add_filter( 'get_avatar' , 'myan_OAuth_custom_avatar' , 10 , 4 );
function myan_OAuth_custom_avatar( $avatar, $id_or_email, $size, $alt ) {
	if( get_option('general_oauth_showProfilePic', 'hide') != 'show')
		return $avatar;
		
	$user = false;
	if ( is_numeric( $id_or_email ) ) {
		$id = (int) $id_or_email;
		$user = get_user_by( 'id' , $id );
	} elseif (is_object( $id_or_email )) {
		if ( ! empty( $id_or_email->user_id ) ) {
		$id = (int) $id_or_email->user_id;
		$user = get_user_by( 'id' , $id );
	}
	} else {
		$user = get_user_by( 'email', $id_or_email );	
	}
	if ( $user && is_object( $user ) ) {
		$avatarNew = get_user_meta( $user->data->ID, "oauth_user_profile_pic", true);
		if($avatarNew != '')
			$avatar = "<img alt='{$alt}' src='{$avatarNew}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
	}
	//print_r($avatar);die;
	return $avatar;
}

add_action( 'show_user_profile', 'myan_show_extra_profile_fields'  );
add_action( 'edit_user_profile', 'myan_show_extra_profile_fields' );
 
function myan_show_extra_profile_fields( $user ) { 
$isOAuthUser = get_user_meta($user->ID, 'loggedInViaGeneralOAuth');
if(count($isOAuthUser) == 0)
	return $user;
?> 
<h3>OAUTH profile information</h3>
<table class="form-table">
	<tr>
		<th><label for="image">Contact url</label></th>
	<td>
		<span class="description">
		<?PHP $link = get_user_meta($user->ID, 'oauth_user_link', true); echo "<a href='$link' target='_blank'>$link</a>"; ?>
		</span>
	</td>
	</tr>
	<tr>
		<th><label for="image">Profile pic</label></th>
	<td>
		<span class="description">
		<?PHP $link = get_user_meta($user->ID, 'oauth_user_profile_pic', true); echo "<img width='64px' height='64px' src='$link'/>"; ?>
		</span>
	</td>
	</tr>
</table>
<?PHP
return $user;
}


add_action('wp_ajax_myan_oauthWordpress_login', 'myan_oauthWordpress_login_callback');
add_action('wp_ajax_nopriv_myan_oauthWordpress_login', 'myan_oauthWordpress_login_callback');

function execute_ALSDKFLSDMC347529DFIDK823($OAUTH_PROVIDER, $whereToReturnOnSuccess="")
{	
	try{
		$oauth = new myan_OAuth_Information($OAUTH_PROVIDER, $whereToReturnOnSuccess);
		$oauth->renderHtmlButton();
		$oauth->js_connect_info();
	}catch(Exception $e)
	{
		echo "<script type='text/javascript'>if(console) console.log('Error in providing OAUTH plugin: { $e->getMessage()}')</script>";
	}
}

function returnOAuthPasswordByCreatingUser($username, $displayName, $provider)
{
	$password = get_option('general_oauth_password');
	if($password == false || $password == '')
	{
		$password = rand();
		update_option("general_oauth_password", $password);
	}
	
	if( $provider == 'google')	
		$provider = 'google';
	else if($provider == 'facebook')	
		$provider = 'facebook';
	else
		throw new Exception("Invalid provider provided.");
		
	if ( !username_exists( $username ) )
	{
		$random_password = $password;
		$user_email=$username.'@example.com';
		$display_name = $displayName;
		$role = 'contributor';
		$user_id=wp_insert_user( array('user_login' => $username, 'user_pass'=>$random_password, 'role' => $role, 'user_email'=>$user_email, 
			'first_name' => $displayName, 'display_name'=>$display_name) 
		);
		if( is_wp_error($user_id) )
			throw new Exception("New OAUTH user creation failed. " . $user_id->get_error_message());
			
		$loginInformation = "provider=$provider&id=".substr($username,1);	
		update_user_meta( $user_id, 'loggedInViaGeneralOAuth', $loginInformation );
	}
	return $password;
}

class oauth_options_page {
	function __construct() {
		add_action( 'admin_menu', array( $this, 'admin_menu' ) );
		add_action( 'widgets_init', array( $this, 'widget_menu') );
		add_filter( 'login_message', array( $this, 'login_message_customOAuth') );
	}
	function widget_menu() {
		include_once('oauth_button.php');
		register_widget( 'OAuthButton_Widget' );
	}
	function admin_menu () {
		add_options_page('OAUTH Appid Management','OAUTH Settings','manage_options','general_oauth_appid', array( $this, 'general_oauth_menupage' ) );
		add_options_page('OAUTH Login Information', 'OAUTH Login Manage', 'edit_posts', 'oauth-msg-to-user', array($this, 'msg_to_user'));
		add_options_page("OAUTH User && Post", "OAUTH User && Post", 'edit_posts', 'oauth-post-and-user-import', array($this,'oauth_post_and_user_import') );
	}
	function oauth_post_and_user_import(){
		include_once("oauth_user_or_post.php");
		execute_XCVNSLD284590SDKDF23093XM();
	}
	function login_message_customOAuth() {
		if( is_user_logged_in() == false && function_exists('execute_ALSDKFLSDMC347529DFIDK823'))
		{
			echo '<ul><li style="float:right;list-style:none; margin: 5px;">';
			execute_ALSDKFLSDMC347529DFIDK823('google', get_bloginfo('wpurl').'/wp-admin');
			echo '</li>';
			
			echo '<li style="float:right;list-style:none; margin: 5px;">';
			execute_ALSDKFLSDMC347529DFIDK823('facebook', get_bloginfo('wpurl').'/wp-admin');
			echo '</li></ul>';
		}
	}
	
	
	function general_oauth_menupage(){
		if( isset($_GET['gplus_oauth_appid_value']) )
		{
			update_option("gplus_oauth_appid_value", $_GET['gplus_oauth_appid_value']);
		}
		if( isset($_GET['facebook_oauth_appid_value']) )
		{
			update_option("facebook_oauth_appid_value", $_GET['facebook_oauth_appid_value']);
		}
		if( isset($_GET['general_oauth_password']) )
		{
			update_option("general_oauth_password", $_GET['general_oauth_password']);
		}
		if( isset($_GET['general_oauth_showProfilePic']) )
		{
			update_option("general_oauth_showProfilePic", $_GET['general_oauth_showProfilePic']);
		}
		$pageURL = get_bloginfo('wpurl'). "/wp-admin/options-general.php?page=general_oauth_appid";
		
		echo "<h1>OAUTH password for all user:</h1> <form method='get' action='$pageURL'>";
		$valueForPassword = get_option('general_oauth_password', '123457890');
		echo "<input type='text' name='general_oauth_password' value='$valueForPassword' size='100' onclick='select()' />";
		echo "<input type='hidden' name='page' value='general_oauth_appid'/> <input type='submit' value='Submit'/></form>";
		echo "<br/><strong>Current value:</strong> $valueForPassword";
		
		$valueFromWPGoogle = get_option('gplus_oauth_appid_value', "846969533537-tie2r85mm5267gid458l4p3qv97b75nk.apps.googleusercontent.com");
		echo "<h1>Type a google app id* and submit:</h1> <form method='get' action='$pageURL'>";
		echo "<input type='text' name='gplus_oauth_appid_value' value='$valueFromWPGoogle' size='100' onclick='select()' /> <input type='hidden' name='page' value='general_oauth_appid'/> <input type='submit' value='Submit'/></form>";
		echo "<br/><strong>Current value:</strong> $valueFromWPGoogle";
		
		$valueFromWPFacebook = get_option('facebook_oauth_appid_value', '220636254729676');
		echo "<h1>Type a facebook app id** and submit:</h1> <form method='get' action='$pageURL'>";
		echo "<input type='text' name='facebook_oauth_appid_value' value='$valueFromWPFacebook' size='100' onclick='select()' /> <input type='hidden' name='page' value='general_oauth_appid'/> <input type='submit' value='Submit'/></form>";
		echo "<br/><strong>Current value:</strong> $valueFromWPFacebook";
		
		echo "<br/>*=Get a google app id <a href='https://console.developers.google.com/project' target='_blank'>here</a> or <a href='https://code.google.com/apis/console/b/0/?noredirect&pli=1'>here</a>, and test <a href='https://developers.google.com/apis-explorer/#p/plus/v1/plus.people.get'>here</a>";
		echo "<br/>**=Get a facebook app id <a href='https://developers.facebook.com/' target='_blank'>here</a>, and test <a href='https://developers.facebook.com/tools/explorer/145634995501895'>here</a>";
		
		echo "<h1>Select choice on profile picture display:</h1> <form method='get' action='$pageURL'>";
		$valueForProfilePic = get_option('general_oauth_showProfilePic', 'hide');
		echo "<input type='radio' name='general_oauth_showProfilePic' value='show'>Yes, 'show' from OAUTH-Provider<br>";
		echo "<input type='radio' name='general_oauth_showProfilePic' value='hide'>No, 'hide' it and show default<br>";
		echo "<input type='hidden' name='page' value='general_oauth_appid'/> <input type='submit' value='Submit'/></form>";
		echo "<br/><strong>Current value:</strong> $valueForProfilePic";
	}
	function msg_to_user(){
		echo '<h2>Dear User,</h2>Thank you for creating your account. <br/><br/>If you chose to delete apps for connecting to this site, then please follow the suitable instruction for you:<ol>';
		echo "<li>If you have logged in via <strong>Google OAuth</strong> and wish to disconnect this app, then you can do it <a target='_blank' href='https://www.google.com/accounts/IssuedAuthSubTokens?hl=en'>here</a></li>";
		echo "<li>If you have logged in via <strong>Facebook connect</strong> and wish to disconnect this app, then you can do it <a target='_blank' href='https://www.facebook.com/settings?tab=applications'>here</a></li>";
		echo '</ol>';
		
		echo "<br/><br/>Regards,<br/>-admin.";
	}
}
new oauth_options_page;
?>